import logging
import os, sys
import datetime
import time

import numpy as np
import cv2
from python.Dector.model import Model
from pyhkvqcore import pyhkvqcore as pqc
import MySQLdb


class RealTimeDector(Model):
    def __init__(self, model_path, driver, db_address, db_port, db_username, db_password):
        super().__init__(model_path)
        self.driver = driver
        self.handel = self.driver.Init()
        self.db = MySQLdb.connect(host=db_address, port=db_port, user=db_username, password=db_password, db="ai_yq")

    def call_back_function(self, label, image_name):
        try:
            sql = "INSERT INTO %s (user_id,status_number,img_url,create_time) VALUES (1,%d,'%s','%s')" % (
                "operation_info", label, image_name, datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            )
            print(sql)
            with self.db.cursor() as cursor:
                cursor.execute(sql)
            self.db.commit()
        except Exception as e:
            logging.warning("Insert Error")
            print(e)
            self.db.rollback()
        return None

    def bind_function(self):
        frame = self.driver.Read(self.handel)
        # 判空操作，未读取到视频数据
        cv2.imshow('pyframe', frame)
        cv2.waitKey(1)
        if frame.size <= 1:
            return None
        frame = cv2.resize(frame, (62, 36))
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        return np.array([frame])

    def __del__(self):
        self.driver.Release()
        self.db.close()


if __name__ == '__main__':
    lib_path = 'E:/WorkSpace/HKVQCore/cmake-build-debug/bin'
    sys.path.append(lib_path)
    os.environ['PATH'] = os.environ['PATH'] + ';' + lib_path + ';'
    model_path = "./model/image_model"
    # 本地摄像头
    driver = pqc.Driver("192,168.1.1", 'admin', 'admin', 8000)
    # 海康威视
    # driver=pqc.Driver("192,168.1.1",'admin','admin',8000)
    dector = RealTimeDector(model_path, driver)
    dector.run()
